Most computer languages build input and output into the language itself, but C originally left I/O to compiler implementers.One reason for this was to give implementers the freedom to design I/O functions that best fit the hardware requirements of the target computer. In practice, most implementers based I/O on a set of library functions originally developed for the OS environment, for example, stdio.h.
C++ uses many of its more advanced language features to implement input and output, including classes, derived classes, function overloading, virtual functions, templates, and multiple inheritance.
Just as C implementations come with a standard library of functions, C++ comes with a standard library of classes.
图片描述(最多50字)
The ios_base class represents general properties of a stream, such as whether it's open for reading and whether it's a binary or a text stream.
The ios class is based on ios_base, and it includes a pointer member to a streambuf object.
The streambuf class provides memory for a buffer, along with class methods for filling the buffer, accessing buffer contents, flushing the buffer, and managing the buffer memory.
The ostream class derived from the ios class and provides output methods. cout is a ostream class object.
The istream class derived from the ios class and provides input methods. cin is a istream class object.
The iostream class is based on the istream and ostream class and thus inherits both input and output methods.
The program could read one character from the file, process it, read the next character from the file, and so on. Reading a file a character at a time from a disk requires a lot of hardware activity and is slow. The buffered approach is to read a large chunk from the disk, store the chunk in the buffer, and read the buffer one character at a time. Because it is much quicker to read individual bytes of data from memory than from a had disk, this approach is much faster as well as easier on the hardware. Similarly, in output, a program can first fill the buffer and then transfer the entire block of data to a hard disk, clearing the buffer for the next batch of output. This is called flushing the buffer.
To use these facilities, you use objects of the approriate classes. For example, you use an ostream object such as cout to handle output. Creating such an object opens a stream, automatically creates a buffer, and associates it with the steam. It also makes the class member functions available to you.
The C++ facilities for file input and output are based on the same basic class definitions that cin and cout are based on, you can using ifsteam and ofstream objects for file input and output.
The C++ I/O class package handles file input and output much as it handles standard input and output. To wirte to a file, you create an ofstream object and use the ostream methods, such as the << insertion operator or write(). To read a file, you create an ifstream object and use the istream methods, such as the >> extraction operator or get(). Files require more management than the standard input and output, however. For example, you have to associate a newly opened file with a stream. You can open a file in read-only mode, write-only mode, or read-and-write mode. If you write to a file, you might want to create a new file, replace an old file, or add to an old file. Or you might want to move back and forth through a file. To help handle these tasks, C++ defines several new classes in the fstream(formerly fstream.h) header file, including the ifstream class for file input and the ofstream class for file output.C++ also defines the fstream class for simultaneous file I/O. These classes are derived from the classses in the iostream header file, so objects fo these new classes are able to use the methods you 've already learned.
图片描述(最多50字)
Suppose you want a program to write to a file. You must do the following:
I Create an ofstream object to manage the output stream;
II Associate that object with a particular file;
III Use the object the same way you would use cout; the only difference is that output goes to the file instead of to the screen.
The codes as belows:
ofstream fout;
fout.open("a.txt");
fout << " some contents";
Indeed, because ostream is a base class for the ofstream class, you can use all the ostream methods, including the various insertion operator definitions and the formatting methods and manipulators. The ofstream class uses buffered output, so the program allocates space for an output buffer when it creates an ofstream object such as fout.
Opening a file for output this way creates a new file if there is no file of that name. If a file by that name exists prior to opening it for output, the act of opening it truncates it so that output starts with a clean file.
The requirements for reading a file are much like those for writing to a file:
I Create an ifstream object to manage the input stream;
II Associate that object with a particular file;
III Use the object the same way you would use cin;
The codes as belows:
ifstream fin;
fin.open("a.txt");
char ch;
fin >>ch;
char buf[11];
fin.getline(buf,80);
string line;
getline(fin,line);
Input, like output, is buffered, so creating an ifstream object such as fin creates an input buffer, which the fin object manages. As with output, buffering moves data much faster than byte-by-byte transfer.
Let's look at a short example:
#include <iostream> // not needed for many systems
#include <fstream>
#include <string>
int main()
{
using namespace std;
string filename;
cout << "Enter name for new file: ";
cin >> filename;
// create output stream object for new file and call it fout
ofstream fout(filename.c_str());
fout << "For your eyes only!\n"; // write to file
cout << "Enter your secret number: "; // write to screen
float secret;
cin >> secret;
fout << "Your secret number is " << secret << endl;
fout.close(); // close file
// create input stream object for new file and call it fin
ifstream fin(filename.c_str());
cout << "Here are the contents of " << filename << ":\n";
char ch;
while (fin.get(ch)) // read character from file and
cout << ch; // write it to screen
cout << "Done\n";
fin.close();
std::cin.get();
std::cin.get();
return 0;
}
output:
Enter name for new file: newfile
Enter your secret number: 13
Here are the contents of newfile:
For your eyes only!
Your secret number is 13
Done
Summary:
A stream is a flow of bytes into or out of a program. A buffer is a temporary holding area in memory that acts as an intermediary between a buffer and a file, using large chunks of data of the size most effciently handled by devices such as disk drivers. And information can be transferred between a buffer and a program in a byte-by-byte flow that often is more convenient for the processing done in a program. C++ handles input by connecting a buffered stream to a program and to its source of input. Similary, C++ handles output by connecting a buffered stream to a program and to its output target. The iostream and fstream file constitute an I/O class library that defines a rich set of classes for managing streams. C++ programs that include the iostream file automatically open eight streams, managing them with eight objects. The cin object manages the stadard input stream, which, by default, connects to the standard input device, typically a keyboard. The cout object manages the standard output stream, which ,by default, connects to the standard output device, typically a monitor. The cerr and clog objects manage unbuffered and buffered streams connected to the standard error device, typically a monitor. These four objects have four wide character counterparts, named wcin, wcout, wcerr, and wclog.
The I/O class library provides a variety of useful methods. The istream class defines versions of the extraction operator(>>) that recognize all the basic C++ types and that convert character input to those types. The get() family of methods and the getline() method provide further support for single-character input and for string input. Similarly, the ostream class defines versions of the insertion operator(<<) that recognize all the basic C++ types and that convert them to suitable character output. The put() method provides further support for single-character output. The wistream and wostream classes provide similar support for wide characters.
You can control how a program formats output by using ios_base class methods and by using manipulators(functions that can be concatenated with insertion) defined in the iostream and iomanip files. These methods and manipulators let you control the number base, the field width, the number of decimal places displayed, the system used to display floating-point values, and other elements.
The fstream file provides class definitions that extend the iostream methods to file I/O. The ifstream class derives from the istream class. By associating an ifstream object with a file, you can use all the istream methods for reading the file. Similarly, associating an ofstream object with a file lets you use the ostream methods to write to a file. And associating an fstream object with a file lets you employ both input and output methods with the file.
To associate a file with a stream, you can provide the filename when initializing a file stream object or you can first create a file stream object and then use the open() method to associate the stream with a file. The close() method terminates the connection between a stream and a file. The class constructors and the open() method take an optional second argument that provides the file mode. The file mode determines such things as whether the file is to be read and/or written to, whether opening a file for writing truncates it, whether attempting to open a non-existent file is an error, and whether to use the binary or text mode.
A text file stores all information in character form. For example, numeric values are converted to character representations. The usual insertion and extraction operators, along with get() and getline(), support this mode. A binary file stores all information by usig the same binary representation the computer uses internally. Binary files store data particularly floating-point vlaues, more accurately and compactly than text files. These class methods let you position a file pointer relative to the beginning of a file, relative to the end, or relative to the current position. The tellg() and tellp() methods report the current file position.
The sstream header file defines istringstream and ostringstream classes that let you use istream and ostream methods to extract information from a string and to format information placed into a string.
-End-
本页共87段,10826个字符,10941 Byte(字节)